﻿using Aspose.Cells;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IBusiness_impl
{
    /// <summary>
    /// 净化气。业务处理
    /// </summary>
    /// 创建时间：2022-12-14 09:39:34。作者：王浩力
    public class CleanGasBusiness : BaseBusiness
    {
        readonly ICleanGasDAL cleanGasDAL = ServicesHelpter.GetService<ICleanGasDAL>();
        readonly IOperate_logDAL operate_LogDAL = ServicesHelpter.GetService<IOperate_logDAL>();
        readonly IClean_gas_check_historyDAL clean_Gas_Check_HistoryDAL = ServicesHelpter.GetService<IClean_gas_check_historyDAL>();
        readonly IClean_gas_update_logDAL clean_Gas_Update_LogDAL = ServicesHelpter.GetService<IClean_gas_update_logDAL>();
        readonly ISource_dictDAL source_DictDAL = ServicesHelpter.GetService<ISource_dictDAL>();
        UserBusiness userBusiness = new UserBusiness();

        /// <summary>
        /// 新增一条
        /// </summary>
        /// <param name="clean_Gas"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-14 09:47:58。作者：王浩力
        public IResult Add(Clean_gas clean_Gas)
        {
            clean_Gas.Input_user_id = CurrentLoginUser.Id;
            clean_Gas.Input_user = CurrentLoginUser.User_real_name;
            clean_Gas.O_step = 1;

            //验证参数
            var resultParames = CheckParames(clean_Gas);
            if (resultParames.Code == (int)ResultCode.Fail)
            {
                return resultParames;
            }

            var result = cleanGasDAL.Add(clean_Gas);
            if (result.Code == (int)ResultCode.Success)
            {
                //操作日志
                CurrentLoginUser.E12 = 8;
                CurrentLoginUser.E3 = $"录入净化气";
                CurrentLoginUser.E1 = Convert.ToInt64(result.Data);
                operate_LogDAL.AddOperateLog(CurrentLoginUser);
            }
            return result;
        }

        /// <summary>
        /// 验证参数
        /// </summary>
        /// <param name="clean_Gas"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-15 11:10:24。作者：王浩力
        private IResult CheckParames(Clean_gas clean_Gas)
        {
            if (string.IsNullOrWhiteSpace(clean_Gas.Sample_no))
            {
                return new Result("样品编号不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Well_name))
            {
                return new Result("井站不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Sampling_location))
            {
                return new Result("取样地点不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Air_source))
            {
                return new Result("气源不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Original_sampling_position))
            {
                return new Result("原取样位置不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Net_sampling_position))
            {
                return new Result("净取样位置不可为空");
            }
            if (clean_Gas.Sampling_temperature <= 0)
            {
                return new Result("取样温度不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Sampling_time))
            {
                return new Result("取样时间不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Analysis_time))
            {
                return new Result("分析时间不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Sampling_condiction))
            {
                return new Result("取样条件不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Sampling_user))
            {
                return new Result("取样人不可为空");
            }
            if (!clean_Gas.Analysis_user.HasValue)
            {
                return new Result("分析人不可为空");
            }
            if (string.IsNullOrWhiteSpace(clean_Gas.Analysis_company))
            {
                return new Result("分析单位不可为空");
            }

            //注释。时间：2023-1-13 10:52:46。允许为空
            //if (clean_Gas.Feedgas_percent <= 0)
            //{
            //    return new Result("原料气%不可为空");
            //}

            //if (clean_Gas.Feedgas_mg_per_m3 <= 0)
            //{
            //    return new Result("原料气(mg/m³)不可为空");
            //}
            //if (clean_Gas.Clean_gas_percent <= 0)
            //{
            //    return new Result("净化气%不可为空");
            //}
            //if (clean_Gas.Clean_gas_mg_per_m3 <= 0)
            //{
            //    return new Result("净化气(mg/m³)不可为空");
            //}

            //检查编号重复。创建时间：2023-1-30 10:02:36。
            var where = new Clean_gas();
            PageModel<Clean_gas> page = null;
            if (clean_Gas.E1 == 1) //编辑；
            {
                if (!clean_Gas.E6.Equals(clean_Gas.Sample_no))
                {
                    where.Sample_no = clean_Gas.Sample_no;
                    page = cleanGasDAL.Page(where, 1, 1);
                }
            }
            else
            {
                where.Sample_no = clean_Gas.Sample_no;
                page = cleanGasDAL.Page(where, 1, 1);
            }
            if (page != null && page.Total > 0)
            {
                return new Result("编号重复，请重新编号");
            }

            return new ResultSuccess();
        }

        /// <summary>
        /// 编辑一条记录
        /// </summary>
        /// <param name="clean_Gas"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-14 15:39:38。作者：王浩力
        public IResult Edit(Clean_gas clean_Gas)
        {
            var old = Get(clean_Gas.Id);
            if (old == null)
            {
                return new Result("没有找到记录");
            }

            //创建时间：2023-1-30 10:19:22。参数检查
            clean_Gas.E1 = 1;//标记为编辑
            clean_Gas.E6 = old.Sample_no;

            var pass = CheckParames(clean_Gas);
            if (pass.CodeEnum != ResultCode.Success)
            {
                return pass;
            }

            var result = cleanGasDAL.Edit(clean_Gas);
            if (result.Code == (int)ResultCode.Success)
            {
                //操作日志
                CurrentLoginUser.E12 = 17;
                CurrentLoginUser.E3 = $"编辑了净化气";
                CurrentLoginUser.E1 = clean_Gas.Id; //数据主键
                CurrentLoginUser.E4 = JsonMyHandle.ToJsonStr(old);//被删之前的数据
                CurrentLoginUser.E5 = JsonMyHandle.ToJsonStr(clean_Gas);//被删之后的数据
                operate_LogDAL.AddOperateLog(CurrentLoginUser);
            }
            return result;
        }

        /// <summary>
        /// 审核处理
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-14 22:27:26。作者：王浩力
        public IResult Check(Clean_gas_check_history info)
        {
            if (info == null)
            {
                return new Result("info不可为空");
            }
            if (info.Jing_hua_qi_key == 0)
            {
                return new Result("Jing_hua_qi_key净化气id必须大于0");
            }
            if (info.Check_stat == 0 && string.IsNullOrWhiteSpace(info.Reject_reason))
            {
                return new Result("驳回理由不可为空");
            }
            info.Check_user_id = CurrentLoginUser.Id;
            info.Check_user_name = CurrentLoginUser.User_real_name;
            return clean_Gas_Check_HistoryDAL.Check(info);
        }

        /// <summary>
        /// 校对处理
        /// </summary>
        /// <param name="clean_Gas"></param>
        /// <returns></returns>
        public IResult Proofread(Clean_gas clean_Gas)
        {
            //检查是否修改了数据
            //修改了就保存修改日志
            //没修改就更新状态值就好
            var old = Get(clean_Gas.Id);
            old.Input_user = null;
            old.Input_user_id = 0;
            old.Create_time = "";
            old.Del_time = null;
            old.Proofreader = null;
            old.Proofread_time = null;
            old.O_step = 0;
            string json1 = JsonMyHandle.ToJsonStr(old);

            Clean_gas obj2 = JsonMyHandle.CopyObject<Clean_gas>(clean_Gas);
            obj2.Input_user = null;
            obj2.Input_user_id = 0;
            obj2.Create_time = "";
            obj2.Del_time = null;
            obj2.Proofreader = null;
            obj2.Proofread_time = null;
            obj2.O_step = 0;
            string json2 = JsonMyHandle.ToJsonStr(obj2);

            clean_Gas.Proofreader = CurrentLoginUser.User_real_name;
            clean_Gas.Profread_user_id = CurrentLoginUser.Id;//2023-1-8 22:23:56 添加

            IResult result;
            if (!json1.Equals(json2))
            {
                //已经修改了值
                result = cleanGasDAL.Proofread(clean_Gas, true);
            }
            else
            {
                result = cleanGasDAL.Proofread(clean_Gas);
            }
            return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="where"></param>
        /// <param name="p"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-14 10:07:13。作者：王浩力
        public PageModel<Clean_gas> GetPage(Clean_gas where, int p, int rows)
        {
            if (CurrentLoginUser.Role_id == "校对人")
            {
                where.WorkList = new List<int>() { 1, 3 };
            }
            else if (CurrentLoginUser.Role_id == "审核人")
            {
                where.WorkList = new List<int>() { 2 };
            }

            //添加时间：2023-1-16 16:46:48。
            if (where.O_step != null)
            {
                where.WorkList = new List<int>() { Convert.ToInt32(where.O_step) };
            }

            var page = cleanGasDAL.Page(where, p, rows);
            return page;
        }

        public IResult Delete(long id)
        {
            //检查是否被引用
            var gas = cleanGasDAL.Get(id);
            if (gas == null)
            {
                return new Result("没找到记录");
            }

            //注释时间：2023-1-30 16:41:52。
            //var checkHistory = clean_Gas_Check_HistoryDAL.GetList(id);
            //var logList = clean_Gas_Update_LogDAL.GetList(id);
            //if (logList != null)
            //{
            //    logList = logList.Where(g => g.E_stat != 1).ToList();
            //    if (checkHistory?.Count > 0 || logList?.Count > 0)
            //    {
            //        return new Result("记录被引用，不可删除");
            //    }
            //}

            //if (!string.IsNullOrWhiteSpace(gas.Proofreader))
            //{
            //    return new Result("记录被引用，不可删除");
            //}

            IResult result = null;
            //if (string.IsNullOrWhiteSpace(gas.Proofreader))
            //{
            //    //物理删除
            //    result = cleanGasDAL.Delete(id, true);
            //}
            //else
            //{
            //    result = cleanGasDAL.Delete(id);
            //}
            result = cleanGasDAL.Delete(id);
            if (result.Code == (int)ResultCode.Success)
            {
                //操作日志
                CurrentLoginUser.E12 = 17;
                CurrentLoginUser.E3 = $"删除净化气";
                CurrentLoginUser.E1 = id;
                CurrentLoginUser.E4 = JsonMyHandle.ToJsonStr(gas);//被删之前的数据
                //CurrentLoginUser.E5 = "11112222";//被删之后的数据
                operate_LogDAL.AddOperateLog(CurrentLoginUser);
            }
            return result;
        }

        /// <summary>
        /// 根据主键获取一条
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-14 14:58:47。作者：王浩力
        public Clean_gas Get(long id)
        {
            return cleanGasDAL.Get(id);
        }

        /// <summary>
        /// 获取信息。combox的下拉值将读取到文本用于展示
        /// </summary>
        /// <param name="id">Clean_gas主键</param>
        /// <returns></returns>
        /// 创建时间：2022-12-15 11:45:14。作者：王浩力
        public CleanGasView GetCmboxStr(long id)
        {
            var all = source_DictDAL.GetAll();
            var info = cleanGasDAL.Get(id);
            var userList = userBusiness.GetAllUser();

            //取样条件 sampling_condiction 
            info.Sampling_condictionTxt = all.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Sampling_condiction))?.Item_name;

            //分析单位 analysis_company     
            info.Analysis_companyTxt = all.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Analysis_company))?.Item_name;

            //分析人 analysis_user    
            info.Analysis_userTxt = userList.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Analysis_user))?.User_real_name;

            //原取样位置 original_sampling_position  
            if (Regex.IsMatch(info.Original_sampling_position, "^\\d{19}"))
            {
                info.Original_sampling_positionTxt = all.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Original_sampling_position))?.Item_name;
            }
            else
            {
                info.Original_sampling_positionTxt = info.Original_sampling_position;
            }

            //取样人 sampling_user     
            info.Sampling_userTxt = userList.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Sampling_user))?.User_real_name;

            //取样地点 sampling_location    
            info.Sampling_locationTxt = all.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Sampling_location))?.Item_name;

            //info.Net_sampling_positionTxt = all.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Net_sampling_position))?.Item_name;
            //净取样位置 net_sampling_position        //修改时间：2023-1-15 17:36:46
            if (Regex.IsMatch(info.Net_sampling_position, "^\\d{19}"))
            {
                info.Net_sampling_positionTxt = all.FirstOrDefault(g => g.Id == Convert.ToInt64(info.Net_sampling_position))?.Item_name;
            }
            else
            {
                info.Net_sampling_positionTxt = info.Net_sampling_position;
            }

            //查询电子签名，添加时间：2023-1-8 22:24:46。作者：王浩力

            //分析人，电子签名
            info.E6 = userList.FirstOrDefault(g => g.Id == info.Analysis_user)?.SignatureImgPath;

            //校对人，电子签名
            if (info.Profread_user_id.HasValue && info.Profread_user_id > 0)
            {
                info.E7 = userList.FirstOrDefault(g => g.Id == info.Profread_user_id)?.SignatureImgPath;
            }

            //审核人，电子签名
            var history = clean_Gas_Check_HistoryDAL.GetList(id);
            if (history?.Count > 0)
            {
                var find = history.OrderByDescending(g => g.Id).FirstOrDefault();
                if (find != null)
                {
                    var ckUser = userList.FirstOrDefault(g => g.Id == find.Check_user_id);
                    info.E5 = find?.Check_user_name;//审核人姓名
                    info.E8 = ckUser?.SignatureImgPath; //审核人电子签名图片url
                }
            }
            CleanGasView cleanGasView = new CleanGasView();
            var mapper = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<Clean_gas, CleanGasView>();
            return mapper.Map(info);
        }

        /// <summary>
        /// 获取净化气处理日志列表
        /// </summary>
        /// <param name="cleanGasKey">净化气主键</param>
        /// <returns></returns>
        /// 创建时间：2022-12-15 14:55:57。作者：王浩力
        public List<Clean_gas_check_history> CleanWorkStepLog(long cleanGasKey)
        {
            var info = Get(cleanGasKey);
            //修改记录
            var updateLog = clean_Gas_Update_LogDAL.GetList(cleanGasKey);

            //审核记录
            var checkLog = clean_Gas_Check_HistoryDAL.GetList(cleanGasKey);

            List<Clean_gas_check_history> list = new List<Clean_gas_check_history>();
            list.Add(new Clean_gas_check_history()
            {
                Check_time = info.Create_time,
                Reject_reason = "录入",
                Check_user_name = info.Input_user
            });
            if (!string.IsNullOrWhiteSpace(info.Proofreader))
            {
                list.Add(new Clean_gas_check_history()
                {
                    Check_time = info.Proofread_time,
                    Reject_reason = "校对",
                    Check_user_name = info.Proofreader
                });
            }
            if (updateLog?.Count > 0)
            {
                foreach (var item in updateLog)
                {
                    if (item.E_stat == 1)
                    {
                        continue;
                    }
                    list.Add(new Clean_gas_check_history()
                    {
                        Check_time = item.Create_time,
                        Reject_reason = "校对(编辑)",
                        Check_user_name = item.Update_real_name
                    });
                }
            }
            if (checkLog?.Count > 0)
            {
                foreach (var item in checkLog)
                {
                    string stat = "审核通过";
                    if (item.Check_stat == 0)
                    {
                        stat = "驳回，";
                    }
                    list.Add(new Clean_gas_check_history()
                    {
                        Check_time = item.Check_time,
                        Reject_reason = stat + item.Reject_reason,
                        Check_user_name = item.Check_user_name
                    });
                }
            }

            return list.OrderBy(g => g.Check_time).ToList();
        }

        /// <summary>
        /// 统计样本数量，审核通过的，没有被删除的
        /// </summary>
        /// 创建时间：2023-1-3 09:48:59。作者：王浩力
        public int GetCleanCount()
        {
            return cleanGasDAL.GetCleanCount();
        }

    }
}
